﻿using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using Docx2Epub.Docx.Elements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Docx2Epub.Docx
{
    public class DocParagraph : DocElement
    {
        public List<DocLeafElement> Elements { private set; get; }

        public DocParagraph(Paragraph paragraph)
        {
            this.Elements = new List<DocLeafElement>();
            this.Body = paragraph.InnerText;

            pickupElements(paragraph);
        }

        public string Body { set; get; }

        public override string ToString()
        {
            return this.Body;
        }

        private void pickupElements(Paragraph paragraph)
        {
            foreach(var e in flatten(paragraph))
            {
                Break b = e as Break;
                Text t = e as Text;

                if (b != null && b.Type == BreakValues.Page)
                    Elements.Add(new DocBreak(BreakType.Page));
                else if (b != null && b.Type == BreakValues.Page)
                    Elements.Add(new DocBreak(BreakType.Line));
                else if (t != null)
                    Elements.Add(new DocText(t.Text));
            }

        }

        private IEnumerable<OpenXmlElement> flatten(OpenXmlElement parent)
        {
            foreach (var e in parent.ChildElements)
            {
                if (e.HasChildren)
                    foreach (var g in flatten(e))
                        yield return g;
                else
                    yield return e;
            }
            yield return parent;
        }
    }
}
